package com.wave.wavesystem.serve.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.wave.common.enums.ErrorCode;
import com.wave.common.model.DeleteRequest;
import com.wave.common.model.Result;
import com.wave.common.util.Func;
import com.wave.wavesystem.ai.factory.WavePromptFactory;
import com.wave.wavesystem.ai.rag.WaveMarkDownReader;
import com.wave.wavesystem.serve.enums.post.PostStatusEnum;
import com.wave.wavesystem.serve.pojo.entity.Post;
import com.wave.wavesystem.serve.pojo.entity.User;
import com.wave.wavesystem.serve.pojo.query.PostQuery;
import com.wave.wavesystem.serve.pojo.vo.post.PostCardVO;
import com.wave.wavesystem.serve.service.IPostService;
import com.wave.wavesystem.serve.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/post")
@RequiredArgsConstructor
@Tag(name = "文章接口-PostController")
public class PostController {

    private final IPostService service;
    private final IUserService userService;
    private final WaveMarkDownReader waveMarkDownReader;
    private final VectorStore wavePgVectorStore;

    @Qualifier("doWorkChatClient")
    private final ChatClient doWorkChatClient;

    @PostMapping("/save")
    @Operation(summary = "新增")
    public Result<Post> save(@RequestBody Post entity) {
        if (Func.isAnyEmpty(entity.getTitle(), entity.getContent(), entity.getAuthorId())) {
            return Result.fail(ErrorCode.NEED_PARAMS);
        }
        entity.setStatus(PostStatusEnum.CHECK.getCode());
        String template = WavePromptFactory
                .postApprovalPrompt(String.valueOf(entity.getId()), entity.getContent())
                .getTemplate();
        service.save(entity);
        CompletableFuture.runAsync(() -> {
            doWorkChatClient
                    .mutate()
                    .defaultToolContext(Map.of("postId", entity.getId(), "postContent", entity.getContent()))
                    .build()
                    .prompt(template)
                    .call()
                    .chatResponse();
        });
        return Result.success(entity);
    }

    @PostMapping("/delete")
    @Operation(summary = "通过 ids 删除")
    public Result<Void> delete(@RequestBody DeleteRequest deleteRequest) {
        if (Func.isEmpty(deleteRequest.getIds())) {
            return Result.fail(ErrorCode.NEED_PARAMS);
        }
        List<Long> removeIds = Func.strToLongList(deleteRequest.getIds());
        service.removeByIds(removeIds);
        return Result.success();
    }

    @PostMapping("/modify")
    @Operation(summary = "修改")
    public Result<Post> modify(@RequestBody Post entity) {
        if (Func.isNotEmpty(entity.getStatus()) && entity.getStatus() == PostStatusEnum.PUBLISH.getCode()) {
            entity.setPublishTime(Func.now_YYYY_MM_DD_MM_HH_SS());
        }
        boolean success = service.updateById(entity);
        if (success) {
            Post post = service.getById(entity.getId());
            List<Document> postChunk = waveMarkDownReader.readByMarkDownContent(post.getContent());
            postChunk.forEach(item -> {
                item.getMetadata().put("postId", post.getId());
                item.getMetadata().put("desc", post.getDesc());
                item.getMetadata().put("title", post.getTitle());
            });
            wavePgVectorStore.add(postChunk);
        }
        return Result.success(entity);
    }

    @PostMapping("/addViews")
    @Operation(summary = "增加文章查看数")
    public Result<Void> addViews(@RequestBody String id) {
        service.updateChain().eq(Post::getId, id)
                .set(Post::getViews, "views + 1")
                .update();
        return Result.success();
    }

    @PostMapping("/query")
    @Operation(summary = "根据条件查询")
    public Result<Post> query(@RequestBody PostQuery query) {
        QueryChain<Post> queryChain = service.getQueryChain(query);
        Post entity = service.getOne(queryChain);
        return Result.success(entity);
    }

    @PostMapping("/list")
    @Operation(summary = "列表")
    public Result<List<Post>> list(@RequestBody PostQuery query) {
        QueryChain<Post> queryChain = service.getQueryChain(query);
        List<Post> list = service.list(queryChain);
        return Result.success(list);
    }

    @PostMapping("/page")
    @Operation(summary = "分页")
    public Result<Page<PostCardVO>> page(@RequestBody PostQuery query) {
        Page<PostCardVO> cardVOPage = new Page<>();
        QueryChain<Post> queryChain = service.getQueryChain(query, true);
        Page<Post> page = service.page(new Page<>(query.getPageNum(), query.getPageSize()), queryChain);
        BeanUtils.copyProperties(page, cardVOPage);
        if (Func.isNotEmpty(page.getRecords())) {
            List<PostCardVO> list = page.getRecords().stream().map(item -> {
                PostCardVO postCardVO = new PostCardVO();
                BeanUtils.copyProperties(item, postCardVO);
                if (item.getContent().length() > 200) {
                    postCardVO.setDesc(item.getContent().substring(0, 200));
                } else {
                    postCardVO.setDesc(item.getContent());
                }
                User user = userService.getById(item.getAuthorId());
                postCardVO.setAuthor(user.getUsername());
                postCardVO.setAuthorAvatar(user.getAvatarUrl());
                return postCardVO;
            }).toList();
            cardVOPage.setRecords(list);
        }
        return Result.success(cardVOPage);
    }

    @PostMapping("/admin/page")
    @Operation(summary = "分页")
    public Result<Page<Post>> adminPage(@RequestBody PostQuery query) {
        QueryChain<Post> queryChain = service.getQueryChain(query);
        Page<Post> page = service.page(new Page<>(query.getPageNum(), query.getPageSize()), queryChain);
        return Result.success(page);
    }
}